package gframework.bean.fileChooser;

import gframework.bean.Util;
import gframework.bean.panel.GPanel;
import java.awt.Color;
import java.awt.KeyboardFocusManager;
import java.awt.event.FocusListener;
import java.awt.event.InputMethodListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.util.HashSet;
import javax.swing.JFileChooser;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.filechooser.FileFilter;

public class GFileChooser extends GPanel {

    public final static String OPEN = "Open";
    public final static String SAVE = "Save";
    public final static String FILES = "Files";
    public final static String DIRECTORIES = "Directories";
    private String type = "";
    private String selectionMode = "";
    public txtFileFilter FILTER_TXT = new txtFileFilter();
    public xmlFileFilter FILTER_XML = new xmlFileFilter();
    public FileFilter filter = null;

    public GFileChooser() {
        initComponents();

        setType(OPEN);
        setSelectionMode(FILES);


        traduzirFileChooser();

        setTeclaEnter();
    }

    private void abrir() throws Exception {
        txtArquivo.setText("");

        JFileChooser fileChooser = new JFileChooser();

        if (selectionMode.equals(FILES)) {
            fileChooser.addChoosableFileFilter(filter);
            fileChooser.setFileSelectionMode(javax.swing.JFileChooser.FILES_ONLY);

        } else if (selectionMode.equals(DIRECTORIES)) {
            fileChooser.setFileSelectionMode(javax.swing.JFileChooser.DIRECTORIES_ONLY);
        }

        int retorno = 0;

        if (type.equals(OPEN)) {
            fileChooser.setDialogType(javax.swing.JFileChooser.OPEN_DIALOG);
            fileChooser.setDialogTitle("Abrir");

            retorno = fileChooser.showOpenDialog(this);

        } else if (type.equals(SAVE)) {
            fileChooser.setDialogType(javax.swing.JFileChooser.SAVE_DIALOG);
            fileChooser.setDialogTitle("Salvar");

            retorno = fileChooser.showSaveDialog(this);
        }

        if (retorno == JFileChooser.APPROVE_OPTION) {
            setArquivo(fileChooser.getSelectedFile().getPath());
        }
    }

    public void setFileFilter(FileFilter i_fileFilter) throws Exception {
        filter = i_fileFilter;
    }

    public String getArquivo() {
        return txtArquivo.getText();
    }

    public void setArquivo(String i_caminho) {
        txtArquivo.setText(i_caminho);

        if (txtArquivo.isEnabled() && txtArquivo.isEditable() && txtArquivo.isFocusable()) {
            txtArquivo.setBackground(UIManager.getColor("TextField.background"));
        }
    }

    public void setArquivoBackground(Color color) {
        txtArquivo.setBackground(color);
    }

    @Override
    public void setEnabled(boolean enabled) {
        txtArquivo.setEnabled(enabled);
        btnAbrir.setEnabled(enabled);
    }

    @Override
    public synchronized void addFocusListener(FocusListener l) {
        txtArquivo.addFocusListener(l);
    }

    @Override
    public synchronized void addKeyListener(KeyListener l) {
        txtArquivo.addKeyListener(l);
    }

    @Override
    public synchronized void addInputMethodListener(InputMethodListener il) {
        txtArquivo.addInputMethodListener(il);
    }

    
    
    private void traduzirFileChooser() {
        UIManager.put("FileChooser.lookInLabelMnemonic", "E");
        UIManager.put("FileChooser.lookInLabelText", "Examinar em");
        UIManager.put("FileChooser.saveInLabelMnemonic", "S");
        UIManager.put("FileChooser.saveInLabelText", "Salvar em");
        UIManager.put("FileChooser.upFolderToolTipText", "Um nível acima");
        UIManager.put("FileChooser.upFolderAccessibleName", "Um nível acima");
        UIManager.put("FileChooser.homeFolderToolTipText", "Desktop");
        UIManager.put("FileChooser.homeFolderAccessibleName", "Desktop");
        UIManager.put("FileChooser.newFolderToolTipText", "Criar nova pasta");
        UIManager.put("FileChooser.newFolderAccessibleName", "Criar nova pasta");
        UIManager.put("FileChooser.listViewButtonToolTipText", "Lista");
        UIManager.put("FileChooser.listViewButtonAccessibleName", "Lista");
        UIManager.put("FileChooser.detailsViewButtonToolTipText", "Detalhes");
        UIManager.put("FileChooser.detailsViewButtonAccessibleName", "Detalhes");
        UIManager.put("FileChooser.fileNameLabelMnemonic", "N");
        UIManager.put("FileChooser.fileNameLabelText", "Nome do arquivo");
        UIManager.put("FileChooser.filesOfTypeLabelMnemonic", "A");
        UIManager.put("FileChooser.filesOfTypeLabelText", "Arquivos do tipo");
        UIManager.put("FileChooser.fileNameHeaderText", "Nome");
        UIManager.put("FileChooser.fileSizeHeaderText", "Tamanho");
        UIManager.put("FileChooser.fileTypeHeaderText", "Tipo");
        UIManager.put("FileChooser.fileDateHeaderText", "Data");
        UIManager.put("FileChooser.fileAttrHeaderText", "Atributos");
        UIManager.put("FileChooser.cancelButtonText", "Cancelar");
        UIManager.put("FileChooser.cancelButtonMnemonic", "C");
        UIManager.put("FileChooser.cancelButtonToolTipText", "Cancelar");
        UIManager.put("FileChooser.openButtonText", "Abrir");
        UIManager.put("FileChooser.openButtonEnable", "false");
        UIManager.put("FileChooser.openButtonMnemonic", "A");
        UIManager.put("FileChooser.openButtonToolTipText", "Abrir");
        UIManager.put("FileChooser.saveButtonText", "Salvar");
        UIManager.put("FileChooser.saveButtonToolTipText", "S");
        UIManager.put("FileChooser.saveButtonToolTipText", "Salvar");
        UIManager.put("FileChooser.updateButtonText", "Alterar");
        UIManager.put("FileChooser.updateButtonToolTipText", "A");
        UIManager.put("FileChooser.updateButtonToolTipText", "Alterar");
        UIManager.put("FileChooser.helpButtonText", "Ajuda");
        UIManager.put("FileChooser.helpButtonToolTipText", "A");
        UIManager.put("FileChooser.helpButtonToolTipText", "Ajuda");
        UIManager.put("FileChooser.acceptAllFileFilterText", "Todos os arquivos");
    }

    @Override
    public void requestFocus() {
        txtArquivo.requestFocus();
    }

    public void setTeclaEnter() {
        HashSet kTab = new HashSet(1);
        kTab.add(KeyStroke.getKeyStroke("TAB"));
        kTab.add(KeyStroke.getKeyStroke("ENTER"));

        txtArquivo.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, kTab);
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        gButton1 = new gframework.bean.button.GButton();
        txtArquivo = new javax.swing.JTextField();
        btnAbrir = new gframework.bean.button.GButton();

        setBorder(null);
        setPreferredSize(new java.awt.Dimension(285, 21));

        txtArquivo.setPreferredSize(new java.awt.Dimension(331, 20));
        txtArquivo.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtArquivoFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtArquivoFocusLost(evt);
            }
        });
        txtArquivo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtArquivoKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtArquivoKeyTyped(evt);
            }
        });

        btnAbrir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gframework/img/abrir.png"))); // NOI18N
        btnAbrir.setMnemonic('a');
        btnAbrir.setText("");
        btnAbrir.setToolTipText("Abrir");
        btnAbrir.setFocusable(false);
        btnAbrir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAbrirActionPerformed(evt);
            }
        });
        btnAbrir.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                btnAbrirFocusLost(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .add(txtArquivo, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 255, Short.MAX_VALUE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(btnAbrir, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 24, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(txtArquivo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(btnAbrir, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 20, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(0, 0, 0))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnAbrirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAbrirActionPerformed
        try {
            abrir();

        } catch (Exception ex) {
            Util.exibirMensagemErro(ex.getMessage(), "VRFileChooser");
        }
    }//GEN-LAST:event_btnAbrirActionPerformed

    private void txtArquivoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtArquivoKeyPressed
        try {
            if (evt.getKeyCode() == KeyEvent.VK_F9) {
                abrir();
            }

        } catch (Exception ex) {
            Util.exibirMensagemErro(ex.getMessage(), "VRFileChooser");
        }
}//GEN-LAST:event_txtArquivoKeyPressed

    private void txtArquivoFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtArquivoFocusGained
        if (txtArquivo.isEditable()) {
            Runnable doSelect = new Runnable() {
                public void run() {
                    txtArquivo.selectAll();
                }
            };

            SwingUtilities.invokeLater(doSelect);
        }
    }//GEN-LAST:event_txtArquivoFocusGained

    private void txtArquivoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtArquivoFocusLost
        try {
            if (!txtArquivo.getText().equals("")) {
                File file = new File(txtArquivo.getText());

                if (selectionMode.equals(FILES)) {
                    if (!file.exists() || !file.isFile()) {
                        throw new Exception("Arquivo inválido!");
                    }
                } else if (selectionMode.equals(DIRECTORIES)) {
                    if (!txtArquivo.getText().endsWith("\\")) {
                        txtArquivo.setText(txtArquivo.getText() + "\\");
                    }

                    if (!file.exists() || !file.isDirectory()) {
                        throw new Exception("Diretório inválido!");
                    }
                }
            }

        } catch (Exception ex) {
            Util.exibirMensagemErro(ex.getMessage(), "VRFileChoser");

            Runnable doFocus = new Runnable() {
                public void run() {
                    txtArquivo.requestFocus();
                }
            };

            SwingUtilities.invokeLater(doFocus);
        }
    }//GEN-LAST:event_txtArquivoFocusLost

    private void txtArquivoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtArquivoKeyTyped
        if (txtArquivo.isEnabled() && txtArquivo.isEditable() && txtArquivo.isFocusable()) {
            txtArquivo.setBackground(UIManager.getColor("TextField.background"));
        }
    }//GEN-LAST:event_txtArquivoKeyTyped

    private void btnAbrirFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_btnAbrirFocusLost
        if (!txtArquivo.getText().endsWith("\\")) {
            txtArquivo.setText(txtArquivo.getText() + "\\");
        }
    }//GEN-LAST:event_btnAbrirFocusLost
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private gframework.bean.button.GButton btnAbrir;
    private gframework.bean.button.GButton gButton1;
    private javax.swing.JTextField txtArquivo;
    // End of variables declaration//GEN-END:variables

    public void setType(String dialogType) {
        this.type = dialogType;
    }

    public String getType() {
        return type;
    }

    public String getSelectionMode() {
        return selectionMode;
    }

    public void setSelectionMode(String selectionMode) {
        this.selectionMode = selectionMode;
    }

    public class txtFileFilter extends FileFilter {

        public static final String FILE_EXTENSION = ".txt";

        public boolean accept(File f) {
            return f.getName().toLowerCase().endsWith(FILE_EXTENSION) || f.isDirectory();
        }

        public String getDescription() {
            return "Documentos de texto (*" + FILE_EXTENSION + ")";
        }
    }

    public class xmlFileFilter extends FileFilter {

        public static final String FILE_EXTENSION = ".xml";

        public boolean accept(File f) {
            return f.getName().toLowerCase().endsWith(FILE_EXTENSION) || f.isDirectory();
        }

        public String getDescription() {
            return "Extensible Markup Language (*" + FILE_EXTENSION + ")";
        }
    }
}